﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace Com.Charence.PassManager.Common.Extensions
{
    public static class Extension
    {
        public static string Encrypt(this string source)
        {
            var sourceBytes = Encoding.UTF8.GetBytes(source);

            X509Certificate2 cert = new X509Certificate2(Path.Combine(
                AppDomain.CurrentDomain.BaseDirectory, "bin", ConfigurationManager.AppSettings["PublicCertificate"]));
            RSACryptoServiceProvider provider = (RSACryptoServiceProvider)cert.PublicKey.Key;
            var encryptedBytes = provider.Encrypt(sourceBytes, false);

            return Convert.ToBase64String(encryptedBytes);
        }

        public static string Decrypt(this string encryptString)
        {
            var encryptBytes = Convert.FromBase64String(encryptString);
            var privateKeyPath = Path.Combine(
                AppDomain.CurrentDomain.BaseDirectory, "bin", ConfigurationManager.AppSettings["PrivateCertificate"]);
            //X509Certificate2 cert = new X509Certificate2(privateKeyPath,
            //       ConfigurationManager.AppSettings["PrivateKeyPass"],
            //       X509KeyStorageFlags.Exportable);

            //RSACryptoServiceProvider provider = (RSACryptoServiceProvider)cert.PrivateKey;

            var providerXml = @"
<RSAKeyValue>
	<Modulus>0VpSUleA3ukt6oxEOQMYjJSvY9WaTm+7lm1JJ3y00tc8VA+YsPHJ80EidAv18Fv4xVXPR1xFuBeKL/88cgMXxvPJOgRxXgbA26DSbLWSnHi6pLFwlp1o5d3VYkgq9SEjv9cCYAVaJeEptiXWa1m5vHJ3d1/gI+nye+kUaF5jVU0=</Modulus>
	<Exponent>AQAB</Exponent>
	<P>82Q2TgwtaWi0IYcw0j//euuMfBxcP2DmtJB0DJ1jeI0wzRAjHlHctiARnWhtp3IvploCalVTMGe0Scr4lv/NdQ==</P>
	<Q>3DKy5DmfXtCPcg44SE33oCFeXtFgE1ScQYuEuYKZrFA6brujbrW2/HtMRU8AO2cRy6oL3uGPnPAbc0Qqqeo1eQ==</Q>
	<DP>7imUXgDaevfis6A3LLVFCIHvYQ7bUYU/m1ZyyFlGGZOHOlHdG3EdWPW+Ztnl2uEIMW6ISIaftZD0wPSlFhTPdQ==</DP>
	<DQ>fPRwO77PR3jGzgxvt+g2qzIEYX4jLRUIjtFjgfowxm3Imunz9nE74878GyCXmx4EJTTcA6CwZHiEu0Zlh4KW0Q==</DQ>
	<InverseQ>BihjzmGh1oVond45fHmmByYq210CM02qNmiQMxS8fiTjmLK+DnimEPtGC4VQaDw91wLBhyE7NElQXXg2d1GsgA==</InverseQ>
	<D>z55Fecex1F9n2+3TUr8RP4nNDrMtXpBMdvhWzkRMh7RQ7gSxpvmDEC0OYAvkkcSESB+7ese1lMYzkzoK1f7fOfGVvLVR468hhdfLJKI9z0nCGkT0bEwc7v9jz5DaE+kqTonHchfzu2lUXY/jUfbs1M8zpYqFvD8D3a+iYlLCmME=</D>
</RSAKeyValue>
";
            RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
            provider.FromXmlString(providerXml);
            byte[] data = provider.Decrypt(encryptBytes, false);

            return Encoding.UTF8.GetString(data);

        }
    }
}
